/**
 * 资产列表筛选
 */
<template>
	<u-dropdown class="fa-dropdown bg-ff" ref="uDropdown" :class="{'over-hid': openDropdown}" active-color="#2E73E5" inactive-color="#2A2A2A" menu-icon-size="24" :border-bottom="true" @open="openDrop" @close="closeDrop">
		<u-dropdown-item :title="areaTitle">
			<view class="slot-content bg-ff p-1">
				<scroll-view scroll-y="true" style="max-height: 900rpx;">
					<ul class="fa-sc-list">
						<li v-for="(item, idx) in area" :key="item.ID" :class="{active : item.check}" @click="checkItem(item, 'area')">{{ item.OrgName }}</li>
						<li style="width:0;height: 0;padding: 0;"></li>
					</ul>
				</scroll-view>
				<u-row gutter="0" class="pt-1 u-border-top">
					<u-col span="3" class="text-center">
						<view class="font28" @click="resetCheckData(1)"><u-icon class="pr-m1" name=" iconfont icon-icon_Reset" size="40"></u-icon>重置</view>
					</u-col>
					<u-col span="9"><u-button class="btn-grad" type="primary" @click="confirm(1)" shape="circle">查看</u-button></u-col>
				</u-row>
			</view>
		</u-dropdown-item>
		<u-dropdown-item :title="typeTitle">
			<view class="slot-content bg-ff px-1 pb-1 pt-m2">
				<scroll-view scroll-y="true" style="max-height: 900rpx;">
					<view class="pb-m2 f-w700">一级分类</view>
					<ul class="fa-sc-list">
						<li v-for="(item, idx) in typeArray" :key="idx" :class="{active : item.check || item.childCheck}" @click="checkItem(item, 'type')">
							{{ item.DictItemValue }}
							<u-badge v-if="item.count" type="success" :count="item.count" bgColor="#2979FF" :offset="[-8, -8]"></u-badge>
						</li>
						<li style="width:0;height: 0;padding: 0;"></li>
					</ul>
					<template v-if="typeChildren.length > 0">
						<view class="pb-m2 f-w700">{{ curTypeName }}的二级分类</view>
						<ul class="fa-sc-list">
							<li v-for="(item, idx) in typeChildren" :key="idx" :class="{active : item.check}" @click="checkChildrenItem(item)">{{ item.DictItemValue }}</li>
							<li style="width:0;height: 0;padding: 0;"></li>
						</ul>
					</template>
				</scroll-view>
				<u-row gutter="0" class="pt-1 u-border-top">
					<u-col span="3" class="text-center">
						<view class="font28" @click="resetCheckData(2)"><u-icon class="pr-m1" name=" iconfont icon-icon_Reset" size="40"></u-icon>重置</view>
					</u-col>
					<u-col span="9"><u-button class="btn-grad" type="primary" @click="confirm(2)" shape="circle">查看</u-button></u-col>
				</u-row>
			</view>
		</u-dropdown-item>
		<u-dropdown-item :title="dateTitle">
			<view class="slot-content bg-ff px-1 pb-1 pt-m2">
				<view class="pb-m2 f-w700">常用时间</view>
				<ul class="fa-sc-list fa-sc-date">
					<li v-for="(item, idx) in date" :key="item.id" :class="{active : item.check}" @click="checkItem(item, 'date')">{{ item.name }}</li>
				</ul>
				<view class="pb-m2 f-w700">自定义时间</view>
				<view class="mb-1">
					<u-row gutter="0">
						<u-col span="5.5">
							<view style="background-color: #F6F8FB;" class="p-min text-center" :class="{'col-gray': startDate == '起始时间'}" @click="showDate(1)">{{ startDate }}</view>
						</u-col>
						<u-col span="1" class="text-center"><text>至</text></u-col>
						<u-col span="5.5">
							<view style="background-color: #F6F8FB;" class="p-min text-center" :class="{'col-gray': endDate == '结束时间'}" @click="showDate(2)">{{ endDate }}</view>
						</u-col>
					</u-row>
				</view>
				<u-row gutter="0" class="pt-1 u-border-top">
					<u-col span="3" class="text-center">
						<view class="font28" @click="resetCheckData(3)"><u-icon class="pr-m1" name=" iconfont icon-icon_Reset" size="40"></u-icon>重置</view>
					</u-col>
					<u-col span="9"><u-button class="btn-grad" type="primary" @click="confirm(3)" shape="circle">查看</u-button></u-col>
				</u-row>
			</view>
		</u-dropdown-item>
		<u-dropdown-item :title="statusTitle">
			<view class="slot-content bg-ff p-1">
				<ul class="fa-sc-list">
					<li v-for="(item, idx) in status" :key="idx" :class="{active : item.check}" @click="checkItem(item, 'status')">{{ item.DictItemValue }}</li>
					<li style="width:0;height: 0;padding: 0;"></li>
				</ul>
				<u-row gutter="0" class="pt-1 u-border-top">
					<u-col span="3" class="text-center">
						<view class="font28" @click="resetCheckData(4)"><u-icon class="pr-m1" name=" iconfont icon-icon_Reset" size="40"></u-icon>重置</view>
					</u-col>
					<u-col span="9"><u-button class="btn-grad" type="primary" @click="confirm(4)" shape="circle">查看</u-button></u-col>
				</u-row>
			</view>
		</u-dropdown-item>
	</u-dropdown>
</template>

<script>
	export default {
		props: {
			area: {
			    type: Array,
				default: []
			},
			status: {
			    type: Array,
				default: []
			},
			type: {
			    type: Array,
				default: []
			},
			startDate: {
			    type: String,
				default: ''
			},
			endDate: {
			    type: String,
				default: ''
			},
			resetFilter: { // 重置筛选条件
				type: Number,
				default: 0
			},
			recordOpen: { // 记录当前是否打开了日期控件，用于控制今天/一周/30天激活
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				showDatePicker: false,
				openDropdown: true,
				areaTitle: '房产',
				typeTitle: '类型',
				dateTitle: '录入时间',
				statusTitle: '状态',
				curTypeName: '',
				typeParent: null,
				typeChildren: [],
                                typeArray:[],
				date: [
					{id: 1, name: '今天', check: false},
					{id: 7, name: '最近一周', check: false},
					{id: 30, name: '最近一个月', check: false},
					{id: "all", name: '全部', check: false}
				],
				cacheFilter: {
					area: null,
					type: null,
					date: null,
					status: null
				}
			}
		},
		created() {
			
		},
		mounted() {
			setTimeout(() => {
				this.cacheFilterData()
			}, 800);
		},
		watch: {
			type: {
				handler: function(value, oldValue) {
					this.typeArray = value;
					this.cacheFilterData();
				},
				immediate: true,
				deep: true
			},
			startDate(nVal, oVal) {
				if (this.recordOpen && this.startDate != '起始时间') {
					this.date.forEach(ele => {
						ele.check = false
					})
					this.$emit('funRecord');
				}
			},
			endDate(nVal, oVal) {
				if (this.recordOpen && this.endDate != '结束时间') {
					this.date.forEach(ele => {
						ele.check = false
					})
					this.$emit('funRecord');
				}
			},
			resetFilter(nVal, oVal) {
				if (nVal > 0) {
					for (let i = 0; i < 4; i++) {
						this.resetCheckData(i+1, 'search');
					}
					this.cacheFilterData();
				}
			}
		},
		
		methods: {
			// 选择某个筛选条件
			checkItem(data, info) {
				if (data.children) {
					this.curTypeName = data.DictItemValue;
					this.typeParent = data; // 将当前父类传递做标识（二级类有选中时，需要更改父类下二级类选中的数量）
					this.typeChildren = data.children; // 类型筛选存在二级选项的，给二级列表赋值渲染
				} else {
					// 类型筛选存在二级选项，没有二级选项的类型则移除当前显示的二级选项
					if (info == 'type') {
						this.typeChildren = [];
					}
					// 日期期间只支持单选
					if (info == 'date') {
						this.date.forEach((ele) => {
							ele.check = false;
						})
						// 点击任意一个时间区间-清空开始结束时间
						this.$emit('funDate', data.id == 1 ? 0 : data.id)
					}
					// 状态单选
					if (info == 'status') {
						this.status.forEach((ele) => {
							ele.check = false;
						})
					}
					// 选中、未选赋值
					data.check = !data.check;
				}
			},
			
			// 类型筛选-选择二级选项
			checkChildrenItem(data) {
				// 选择'全部'时，当前模块所有item.check=false
				if (data.DictGuid == '') {
					let all = !this.typeChildren[0].check;
					all ? this.typeParent.check = true : this.typeParent.check = false; // 二级类全选时 设置父类check=true
					this.typeChildren.forEach((ele) => {
						if (all) {
							ele.check = true;
						} else {
							ele.check = false;
						}
					})
					// 计算父类右上角显示选中数量
					this.calculationCheckCount();
					return
				}
				// 非点击全部时
				// 选中、未选赋值
				data.check = !data.check;
				// 检查是否需要激活全部button/部分未选则不激活
				this.checkChildrenActiveAll();
				// 计算父类右上角显示选中数量
				this.calculationCheckCount();
			},
			
			// 检查二级筛选是否需要激活全部/部分未选则不激活全部并对应的重对应的一级类
			checkChildrenActiveAll() {
				let newData = JSON.stringify(this.typeChildren);
				let checkData = JSON.parse(newData).splice(1, JSON.parse(newData).length-1)
				let active = checkData.every(v => v.check) // 判断每一选是否选中
				if (active) { // 二级类全部选中
					this.typeChildren[0].check = true;
					this.typeParent.check = true;
				} else {
					this.typeChildren[0].check = false;
					this.typeParent.check = false;
				}
				return active
			},
			
			// 计算二级类中选中的数量
			calculationCheckCount() {
				let newData = JSON.stringify(this.typeChildren);
				let checkData = JSON.parse(newData).splice(1, JSON.parse(newData).length-1)
				let arr = checkData.filter(v => v.check).map(v => v.DictItemValue);
				if (arr.length >= 1) {
					this.typeParent.childCheck = true
				} else {
					this.typeParent.childCheck = false
				}
				this.$set(this.typeParent, "count", arr.length);
			},
			
			// 显示日期插件
			showDate(idx) {
				let open = false;
				open = !this.showDatePicker
				let obj = {
					index: idx,
					show: open
				}
				this.$emit('funCalendar', obj)
			},
			
			// 重置选项
			resetCheckData(num, msg) {
				let newData = null;
				num == 1 ? newData = this.area : 
				num == 2 ? newData = this.typeArray : 
				num == 3 ? newData = this.date : 
				num == 4 ? newData = this.status : null
				
				if (msg == 'search') {
					num == 1 ? this.areaTitle = '房产' :
					num == 2 ? this.typeTitle = '类型' : 
					num == 3 ? this.dateTitle = '录入时间' : 
					num == 4 ? this.statusTitle = '状态' : null
				}
				
				if (num != 2) {
					newData.forEach(ele => {
						ele.check = false
					})
					num == 3 ? this.$emit('funDate', 'reset') : null; 
				} else { // 类型筛选格式化
					newData.forEach(ele => {
						ele.check = false;
						ele.count ? ele.count = 0 : null
						if (ele.children) {
							ele.childCheck = false;
							ele.children.forEach(v => {
								v.check = false;
							})
						}
					})
				}
			},
			
			// 确定筛选时提取类型的数据
			formatTypeData() {
				let arr = []
				let dict = []
				this.typeArray.forEach(ele => {
					if (ele.check) {
						if (ele.childCheck) {
							ele.children.forEach(v => {
								v.check && v.DictItemValue != '全部' ? arr.push(v.DictItemValue) : null
								v.check && v.DictItemValue != '全部' ? dict.push(v.DictItemKey) : null
							});
						} else {
							arr.push(ele.DictItemValue)
							dict.push(ele.DictItemKey)
						}
					}
					if (!ele.check && ele.childCheck) {
						ele.children.forEach(v => {
							v.check ? arr.push(v.DictItemValue) : null
							v.check ? dict.push(v.DictItemKey) : null
						});
					}
				})
				return {arr, dict}
			},
			
			// 确认筛选
			confirm(idx) {
				let arr = [];
				let key = [];
				switch(idx) {
				    case 1:
						arr = this.area.filter(v => v.check).map(v => v.OrgName);
						key = this.area.filter(v => v.check).map(v => v.ID);
						arr.length == 0 ? this.areaTitle = '房产' : this.areaTitle = arr.join(',');
						this.$emit('funArea', key);
						this.cacheFilter.area = JSON.stringify(this.area);
						break;
						
					case 2:
						let obj = this.formatTypeData();
						obj.arr.length == 0 ? this.typeTitle = '类型' : this.typeTitle = obj.arr.join(',');
						this.$emit('funType', obj);
						this.cacheFilter.type = JSON.stringify(this.typeArray);
						break;
						
					case 3:
						let info = null, txtStart = '起始时间', txtEnd = '结束时间';
						arr = this.date.filter(v => v.check).map(v => v.name);
						// 确定筛选前的选项控制
						if (this.startDate != txtStart || this.endDate != txtEnd) {
							if (this.startDate == txtStart && this.endDate != txtEnd) {
								return uni.showToast({ title: '请选择起始时间', icon: 'none'})
							}
							if (this.startDate != txtStart && this.endDate == txtEnd) {
								return uni.showToast({ title: '请选择结束时间', icon: 'none'})
							}
							if (this.startDate != txtStart && this.endDate != txtEnd && this.startDate > this.endDate) {
								return uni.showToast({
									title: '起始时间不能大于结束时间',
									icon: 'none',
									duration: 2000
								});
							}
							info = {
								sDate: this.startDate,
								eDate: this.endDate
							}
						}
						// 设置title
						if (arr.length == 0 && this.startDate == txtStart) {
							this.dateTitle = '录入时间'
						} else {
							arr.length > 0 ? this.dateTitle = arr.join(',') : this.dateTitle = '自定义时间';
						}
						this.$emit('funDate', info);
						this.cacheFilter.date = JSON.stringify(this.date);
						break;
						
					case 4:
						arr = this.status.filter(v => v.check).map(v => v.DictItemValue);
						key = this.status.filter(v => v.check).map(v => v.DictItemKey);
						arr.length == 0 ? this.statusTitle = '状态' : this.statusTitle = arr.join(',');
						this.$emit('funStatus', key);
						this.cacheFilter.status = JSON.stringify(this.status);
						break;
				}
				this.$refs.uDropdown.close();
			},
			
			// 打开Drop
			openDrop(num) {
				this.openDropdown = false;
				if (num == 0) {
					this.$emit('funOpen', this.cacheFilter.area, num)
				}else if (num == 1) {
					this.typeChildren = [];
					this.$emit('funOpen', this.cacheFilter.type, num)
				}else if (num == 2) {
					this.date = JSON.parse(this.cacheFilter.date);
				}else {
					this.$emit('funOpen', this.cacheFilter.status, num)
				}
			},
			
			// 关闭Drop
			closeDrop() {
				this.openDropdown = true;
			},
			
			// 缓冲数据
			cacheFilterData() {
				this.cacheFilter.area = JSON.stringify(this.area);
				this.cacheFilter.type = JSON.stringify(this.typeArray);
				this.cacheFilter.date = JSON.stringify(this.date);
				this.cacheFilter.status = JSON.stringify(this.status);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.fa-dropdown {
		.fa-sc-list {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-between;
			li {
				position: relative;
				flex: 0 0 28%;
				display: inline-block;
				margin-bottom: 26rpx;
				font-size: 24rpx;
				color: #2A2A2A;
				text-align: center;
				background-color: #F6F8FB;
				border-radius: 4rpx;
				padding: 17rpx 6rpx;
			}
		}
		.fa-sc-date {
			li {
				flex: 0 0 20%;
			}
		}
		.active {
			background-color: #ECF4FF !important;
			color: #2E73E5 !important;
		}
	}
</style>
